import { request, GET, POST } from '../utils/request';
import { getCookies, setCookies, deleteCookie } from '../utils/cookie'

export function getUser() {
  const { userid, token } = getCookies();
  if (!token) return;
  const headers = {
    'Authorization': `Bearer ${token}`
  }
  return GET(`/api/v1/users/${userid}`, headers);
}

export function updateUser(userInfo) {
  const { userid, token } = getCookies();
  console.log(userInfo);
  const len = Object.keys(userInfo).length;
  if (!token || len === 0) return;
  const headers = {
    'Authorization': `Bearer ${token}`
  }
  let url = `/api/v1/users/${userid}/edit?`;
  let index = 0;
  for (const key in userInfo) {
    index += 1;
    if (userInfo.hasOwnProperty(key)) {
      url += `${key}=${userInfo[key]}`
    }
    if (index < len) url += '&';
  }
  return GET(url, headers);
}

export function getUserCookie() {
  const { userid, username, roll, token } = getCookies();
  return {
    userid,
    username,
    roll,
    token
  }
}

export function logout() {
  deleteCookie();
}

export function register(userid, username, password, phone, group) {
  console.log("register: " + username)
  const roll = 2;
  return GET(`/api/v1/register?userid=${userid}&username=${username}&password=${password}&phone=${phone}&roll=${roll}&group=${group}`);
}

export function login(username, password) {
  console.log("login: " + username)
  return GET(`/api/v1/login?username=${username}&password=${password}`);
}

export function saveToken({userid, username, group, roll, token}) {
  setCookies(userid, username, group, roll, token);
}
